<template>
  <div>
    <component
      :is="remote"
      v-bind="$attrs"
      v-if="remote"
      v-model="name"
      @parentEvent="parentEvent"
    ></component>
  </div>
</template>

<script>
import * as Vue from "vue";
import { loadModule } from "vue3-sfc-loader/dist/vue2-sfc-loader";

export default {
  name: "App",
  data() {
    return {
      name: "李四",
      remote: null,
      url: "http://localhost:3000/getVue2Str",
    };
  },
  mounted() {
    this.load(this.url);
  },
  watch: {
    name(newName) {
      console.log(newName, "监听到变化");
    },
  },
  methods: {
    // 加载
    async load(url) {
      let res = await fetch(url).then((res) => res.json());

      const options = {
        moduleCache: {
          vue: Vue,
        },
        async getFile() {
          return res.fileStr;
        },
        addStyle(textContent) {
          const style = Object.assign(document.createElement("style"), {
            textContent,
          });
          const ref = document.head.getElementsByTagName("style")[0] || null;
          document.head.insertBefore(style, ref);
        },
      };

      // 加载远程组件
      this.remote = await loadModule(res.fileName || "loader.vue", options);
    },
    // 子组件调用
    parentEvent() {
      console.log("父组件事件触发");
    },
  },
};
</script>
